package com.daxt.common.config.minio;

import io.minio.*;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 文件服务器工具类
 */
@Component
public class MinIoUtil {

    @Autowired
    private MinioClient minioClient;

    /**
     * 查看存储bucket是否存在
     *
     * @return boolean
     */
    public Boolean bucketExists(String bucketName) {
        Boolean found;
        try {
            found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            //e.printStackTrace();
            return false;
        }
        return found;
    }

    /**
     * 创建存储bucket
     *
     * @return Boolean
     */
    public Boolean makeBucket(String bucketName) {
        try {
            minioClient.makeBucket(MakeBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 删除存储bucket
     *
     * @return Boolean
     */
    public Boolean removeBucket(String bucketName) {
        try {
            minioClient.removeBucket(RemoveBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 获取全部bucket
     */
    public List<Bucket> getAllBuckets() {
        try {
            return minioClient.listBuckets();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 文件上传
     *
     * @param file 文件
     * @return Boolean
     */
    public Boolean upload(String bucketName, String fileName, MultipartFile file, InputStream inputStream) {
        try {
            PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(bucketName).object(fileName)
                    .stream(inputStream, file.getSize(), -1).contentType(file.getContentType()).build();
            //文件名称相同会覆盖
            minioClient.putObject(objectArgs);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 文件上传
     *
     * @return Boolean
     */
    public Boolean upload(String bucketName, String fileName, InputStream inputStream) {
        try {

//            PutObjectArgs objectArgs = PutObjectArgs.builder().object("111.pdf")
//                    .bucket("static")
//                    .contentType("application/octet-stream")
//                    .stream(inputStream,inputStream.available(),-1).build();
            PutObjectArgs objectArgs = PutObjectArgs.builder().object(fileName)
                    .bucket(bucketName)
                    .contentType("application/octet-stream")
                    .stream(inputStream,inputStream.available(),-1).build();

            //文件名称相同会覆盖
            minioClient.putObject(objectArgs);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 预览图片
     *
     * @param fileName
     * @return
     */
    public String preview(String fileName, String bucketName) {
        // 查看文件地址
        GetPresignedObjectUrlArgs build = new GetPresignedObjectUrlArgs().builder().bucket(bucketName).object(fileName).method(Method.GET).build();
        try {
            String url = minioClient.getPresignedObjectUrl(build);
            return url;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 文件下载
     *
     * @param fileName 文件名称
     * @param bucketName      bucketName
     * @return Boolean
     */
    public InputStream download(String fileName, String bucketName) {
        GetObjectArgs objectArgs = GetObjectArgs.builder().bucket(bucketName)
                .object(fileName).build();
        try {

           InputStream inputStream = minioClient.getObject(objectArgs);
           return inputStream;

        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
//        try (GetObjectResponse response = minioClient.getObject(objectArgs)) {
//            byte[] buf = new byte[1024];
//            int len;
//            try (FastByteArrayOutputStream os = new FastByteArrayOutputStream()) {
//                while ((len = response.read(buf)) != -1) {
//                    os.write(buf, 0, len);
//                }
//                os.flush();
//                byte[] bytes = os.toByteArray();
//                res.setCharacterEncoding("utf-8");
//                //设置强制下载不打开
//                //res.setContentType("application/force-download");
//                res.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
//                try (ServletOutputStream stream = res.getOutputStream()) {
//                    stream.write(bytes);
//                    stream.flush();
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    /**
     * 查看文件对象
     *
     * @return 存储bucket内文件对象信息
     */
    public List<Item> listObjects(String bucketName) {
        Iterable<Result<Item>> results = minioClient.listObjects(
                ListObjectsArgs.builder().bucket(bucketName).build());
        List<Item> items = new ArrayList<>();
        try {
            for (Result<Item> result : results) {
                items.add(result.get());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return items;
    }

    /**
     * 删除
     *
     * @param fileName
     * @return
     * @throws Exception
     */
    public boolean remove(String fileName, String bucketName) {
        try {
            minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(fileName).build());
        } catch (Exception e) {
//            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 批量删除文件对象（没测试）
     *
     * @param objects 对象名称集合
     */
    public Iterable<Result<DeleteError>> removeObjects(List<String> objects, String bucketName) {
        List<DeleteObject> dos = objects.stream().map(e -> new DeleteObject(e)).collect(Collectors.toList());
        Iterable<Result<DeleteError>> results = minioClient.removeObjects(RemoveObjectsArgs.builder().bucket(bucketName).objects(dos).build());
        return results;
    }


    public static void main(String[] args)
            throws IOException, NoSuchAlgorithmException, InvalidKeyException {

        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();

        String updateAssetUrl = "http://192.168.0.200:57142/api/v1/login";
        String jsonParam = " {\"accessKey\":\"minioadmin\",\"secretKey\":\"minioadmin\"}";
        HttpPost httpPost = new HttpPost(updateAssetUrl);
//        httpPost.setHeader("Authorization", "Bearer " + headersAuthor);
        httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
        StringEntity entity = new StringEntity(jsonParam, ContentType.create("text/json", "UTF-8"));
        httpPost.setEntity(entity);
        System.err.println("3333333333:"+entity.toString());

        CloseableHttpResponse closeableHttpResponse = closeableHttpClient.execute(httpPost);

        int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            //状态码非200代表没有正常返回,此处处理你的业务
        }

        Header[] header = closeableHttpResponse.getHeaders("Set-Cookie");
        HttpEntity httpEntity = closeableHttpResponse.getEntity();
        String asset_synchronization = EntityUtils.toString(httpEntity, "UTF-8");
//        JSONArray jsonArray = JSONArray.parseArray(asset_synchronization);
//        if (jsonArray.size() > 0) {
//            //判断返回的json数组是否不为空,此处即可处理你的业务
//        }


        //Set-Cookie: token=ABvCZRMu8jD4aYaXiL/hdKY6BA8eqBMaPEnMN1YG0nfsixLnfqt0XZA2pMtmKqhmWBXrAYSBzc8EpyeXlhANAX7SRptFSWrhuObgShk/cSw3Zep2AOZQkZLV1S1TzLoO3qBGliTF5nJr0jDg1KOSqVCM9s+PDV6LA1pCULD9HwY0VmUcWOZ2lGijNqxULuRVai1sG8sGfVoF9EIadKkfSxuLhyXRJFL0WT+rpvvhuefOtux34lZ/BTLBBEjQlWejvDZ0uUnnKBG7jpLjYmFEK0dQtdz7a7Aw2ShVOCIlP9aYEql8SEfsHoBeduT/JXRMoNR00SlIJifA8DpVHO2IcadVYKW53+O0mDwjEZHgLqH1JHmh7YLglctSxj1teu8G60sP+KaZwFnedbyKgpvKxoGGTHPe++aFcQtpN/bmttLu3nnwhUJV4qh0wlC7Y26ntrXp6bJd3d7OoKwVZG5RCzFWVmAJ+LLOPcsPUy/JZzfAasgmnPlG2jdFOZg1lpWZuyo9bAwjWWSBsQRCoimAGeWIzjPz5hT1OcTHybAvd2fhZHbA+FbEej/FYQ==

//        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
//
//        String updateAssetUrl = "http://192.168.0.200:57142/api/v1/admin/info";
//        String jsonParam = " ";
//        HttpGet httpGet = new HttpGet(updateAssetUrl);
//        httpGet.addHeader("C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PcsPUy/JZzfAasgmnPlG2jdFOZg1lpWZuyo9bAwjWWSBsQRCoimAGeWIzjPz5hT1OcTHybAvd2fhZHbA+FbEej/FYQ==");
////        httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
////        StringEntity entity = new StringEntity(jsonParam, ContentType.create("text/json", "UTF-8"));
////        httpPost.setEntity(entity);
////        System.err.println("3333333333:"+entity.toString());
//
//        CloseableHttpResponse closeableHttpResponse = closeableHttpClient.execute(httpGet);
//
//        int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
//        if (statusCode != HttpStatus.SC_OK) {
//            //状态码非200代表没有正常返回,此处处理你的业务
//        }
//
//        Header[] header = closeableHttpResponse.getHeaders("Set-Cookie");
//        HttpEntity httpEntity = closeableHttpResponse.getEntity();
//        String asset_synchronization = EntityUtils.toString(httpEntity, "UTF-8");
//        JSONArray jsonArray = JSONArray.parseArray(asset_synchronization);
//        if (jsonArray.size() > 0) {
//            //判断返回的json数组是否不为空,此处即可处理你的业务
//        }




            // Create a minioClient with the MinIO server playground, its access key and secret key.
//            MinioClient minioClient =
//                    MinioClient.builder()
//                            .endpoint("http://192.168.0.200:9000/")
//                            .credentials("minioadmin", "minioadmin")
//                            .build();

            // Make 'asiatrip' bucket if not exist.
//            boolean found =
//                    minioClient.bucketExists(BucketExistsArgs.builder().bucket("asiatrip").build());
//            if (!found) {
//                // Make a new bucket called 'asiatrip'.
//                minioClient.makeBucket(MakeBucketArgs.builder().bucket("asiatrip").build());
//            } else {
//                System.out.println("Bucket 'asiatrip' already exists.");
//            }

//        try {
//
//            minioClient.
//
//            Iterable<Result<Item>> results = minioClient.listObjects(
//                    ListObjectsArgs.builder().bucket("static").build());
//
//        Iterator<Result<Item>> iter = results.iterator();
//        while (iter.hasNext()){
//            Result<Item> s = iter.next();
//            Item i = s.get();
//            System.err.println("1=:"+i.storageClass());
//        }
//
//        } catch (ErrorResponseException e) {
//            e.printStackTrace();
//        } catch (InsufficientDataException e) {
//            e.printStackTrace();
//        } catch (InternalException e) {
//            e.printStackTrace();
//        } catch (InvalidResponseException e) {
//            e.printStackTrace();
//        } catch (ServerException e) {
//            e.printStackTrace();
//        } catch (XmlParserException e) {
//            e.printStackTrace();
//        }
//        System.err.println("222:");



//            // Upload '/home/user/Photos/asiaphotos.zip' as object name 'asiaphotos-2015.zip' to bucket
//            // 'asiatrip'.
//            minioClient.uploadObject(
//                    UploadObjectArgs.builder()
//                            .bucket("asiatrip")
//                            .object("asiaphotos-2015.zip")
//                            .filename("D:/a/1447475314996285441.pdf")
//                            .build());
//            System.out.println(
//                    "'/home/user/Photos/asiaphotos.zip' is successfully uploaded as "
//                            + "object 'asiaphotos-2015.zip' to bucket 'asiatrip'.");

    }

}

